open Ocamlbuild_plugin
open Ocamlbuild_pack

(*{{{ directories *)
let event_lib_dir = "/usr/local/lib"
(*}}}*)

(*{{{ ocamlfind *)
let pco packages =
  let p = Unix.open_process_in (Printf.sprintf "ocamlfind query -format '-I %%d' %s -separator ' '" (String.concat " " packages)) in
  let result_line = input_line p in
  ignore(Unix.close_process_in p);
  result_line
  
let plo predicates packages = 
  let p = Unix.open_process_in (Printf.sprintf "ocamlfind query -r -predicates %s -format '-I %%d %%a' -separator ' ' %s | sed 's/-I \\/[\\./a-z\\0-9\\-]\\+ unix.cmxa//'" predicates (String.concat " " packages)) in
  let result_line = input_line p in
  ignore(Unix.close_process_in p);
  result_line

let ocamlfind_libs libs = 
  let tag_name = "use_" ^ (String.concat "+" libs) in
  flag ["infer_interface";"ocaml";tag_name]
    (S[Sh(pco libs)]);
  flag ["compile";"ocaml";tag_name]
    (S[Sh(pco libs)]);
  flag ["link";"byte";"ocaml";tag_name]
    (S[Sh(plo "byte" libs)]);
  flag ["link";"native";"ocaml";tag_name]
    (S[Sh(plo "native" libs)])
(*}}}*)

let _ = 
  rule "glade2caml"
    ~dep:"%.glade"
    ~prod:"%.ml"
    begin fun env _ ->
      let glade_file = env "%.glade" in
      let ml_file = Pathname.update_extension "ml" glade_file in
      (
        Printf.printf "GLADE_FILE:%s\n" (Pathname.to_string glade_file);
        Cmd(S[Sh (Printf.sprintf "lablgladecc2 %s > %s" (Pathname.to_string glade_file) (Pathname.to_string ml_file) )]);
      )
    end;
  dispatch begin 
    function 
      | After_rules ->
          ocamlfind_libs ["pcre"];
          ocamlfind_libs ["extlib"];
          ocamlfind_libs ["netstring"];
          ocamlfind_libs ["json-wheel"];
          ocamlfind_libs ["pcre";"json-wheel"];
          ocamlfind_libs ["sexplib"];
          ocamlfind_libs ["sexplib";"camomile"];
          ocamlfind_libs ["type-conv"];
          ocamlfind_libs ["lwt"];
          (* openGL GLUT SDL GTK+ *)
          ocaml_lib ~extern:true ~dir:"+lablGL" "lablgl";
          ocaml_lib ~extern:true ~dir:"+lablGL" "lablglut";
(*           ocaml_lib ~extern:true ~dir:"+lablGL" "glut"; *)
          ocaml_lib ~extern:true ~dir:"+sdl" "sdl";
          ocaml_lib ~extern:true ~dir:"+sdl" "sdlloader";
          ocaml_lib ~extern:true ~dir:"+sdl" "sdlmixer"; 
          ocaml_lib ~extern:true ~dir:"+sdl" "sdlttf"; 
          (*GTK {{{*)
          ocaml_lib ~extern:true ~dir:"+lablgtk2" "lablgtk";
          flag ["link";"ocaml"; "byte"; "use_lablgtk"]
            (S[A "lablgtk.cma";  A "gtkInit.cmo"]);
          ocaml_lib ~extern:true ~dir:"+lablgtk2" "lablgtkgl";
          ocaml_lib ~extern:true ~dir:"+lablgtk2" "lablglade";
          (*}}}*)
      | _ -> ()	    
end

